package a09_贪心算法;

import java.util.Arrays;

/**
 * <p>
 * a12_分发糖果
 * </p>
 *
 * @author flyduck
 * @since 2025/1/13
 */

//1 2 2 5 4 3 2
//先考虑一边：右比左高的情况
//1 2 1 2 1 1 1
//在考虑：左比右高（从后往前遍历，能利用到之前比较的结果）
//为啥从后往前遍历，假设从前往后就会变成
//1 2 1 2 2 2 1
//从后往前
//1 2 1 4 3 2 1
public class a12_分发糖果 {
    public static void main(String[] args) {
        int candy = candy(new int[]{1, 0, 2});
        System.out.println(candy);
    }
    public static int candy(int[] ratings) {
        int[] result = new int[ratings.length];
        result[0] = 1;
        for (int i = 1; i < ratings.length; i++) {
            if(ratings[i] > ratings[i-1]){
                result[i] = result[i-1] + 1;
            }else {
                result[i] = 1;
            }
        }

        for (int i = ratings.length - 2; i >= 0; i--) {
            if(ratings[i] > ratings[i+1] && result[i] <= result[i+1]){
                result[i] = result[i+1] + 1;
            }
        }
        return Arrays.stream(result).sum();
    }
}
